home *** CD-ROM | disk | FTP | other *** search
/ Technotools / Technotools (Chestnut CD-ROM)(1993).ISO / lang_c / tctutor1 / chap11.txt < prev    next >
Text File  |  1987-07-04  |  27KB  |  586 lines

  1.                       Chapter 11 - Structures and Unions
  2.  
  3.  
  4.                             WHAT IS A STRUCTURE?
  5.  
  6.              A structure is a user defined data type.   You have the
  7.         ability  to  define  a new type of  data  considerably  more
  8.         complex than the types we have been using.  A structure is a
  9.         combination  of  several different previously  defined  data
  10.         types,  including other structures we have defined.  An easy
  11.         to  understand definition is,  a structure is a grouping  of
  12.         related  data in a way convenient to the programmer or  user
  13.         of the program.   The best way to understand a structure  is
  14.         to  look  at  an example,  so if you will load  and  display
  15.         STRUCT1.C, we will do just that.
  16.  
  17.              The  program begins with a structure  definition.   The
  18.         key  word  "struct"  is followed by  some  simple  variables
  19.         between  the  braces,   which  are  the  components  of  the
  20.         structure.   After  the  closing brace,  you will  find  two
  21.         variables listed,  namely "boy",  and "girl".   According to
  22.         the  definition  of a structure,  "boy" is  now  a  variable
  23.         composed of three elements,  "initial",  "age", and "grade".
  24.         Each of the three fields are associated with "boy", and each
  25.         can  store a variable of its respective type.   The variable
  26.         "girl"  is also a variable containing three fields with  the
  27.         same  names  as those of "boy" but  are  actually  different
  28.         variables.  We have therefore defined 6 simple variables.
  29.  
  30.                          A SINGLE COMPOUND VARIABLE
  31.  
  32.              Lets  examine  the  variable "boy"  more  closely.   As
  33.         stated above, each of the three elements of "boy" are simple
  34.         variables  and can be used anywhere in a C program  where  a
  35.         variable of their type can be used.   For example, the "age"
  36.         element  is  an integer variable and can therefore  be  used
  37.         anywhere  in a C program where it is legal to use an integer
  38.         variable,  in calculations, as a counter, in I/O operations,
  39.         etc.   The  only problem we have is defining how to use  the
  40.         simple  variable  "age"  which is a  part  of  the  compound
  41.         variable  "boy".   We  use both names with a  decimal  point
  42.         between  them with the major name first.  Thus "boy.age"  is
  43.         the  complete  variable name for the "age" field  of  "boy".
  44.         This  construct can be used anywhere in a C program that  it
  45.         is desired to refer to this field.   In fact,  it is illegal
  46.         to  use the name "boy" or "age" alone because they are  only
  47.         partial definitions of the complete field.  Alone, the names
  48.         refer to nothing.
  49.  
  50.                      ASSIGNING VALUES TO THE VARIABLES
  51.  
  52.              Using  the above definition,  we can assign a value  to
  53.         each  of  the  three fields of "boy" and each of  the  three
  54.         fields  of  "girl".   Note carefully that  "boy.initial"  is
  55.  
  56.  
  57.                                   Page 76
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.                       Chapter 11 - Structures and Unions
  68.  
  69.  
  70.         actually  a "char" type variable,  because it  was  assigned
  71.         that in the structure, so it must be assigned a character of
  72.         data.   Notice  that "boy.initial" is assigned the character
  73.         'R'  in agreement with the above rules.   The remaining  two
  74.         fields of "boy" are assigned values in accordance with their
  75.         respective  types.   Finally  the three fields of  girl  are
  76.         assigned values but in a different order to illustrate  that
  77.         the order of assignment is not critical.
  78.  
  79.                      HOW DO WE USE THE RESULTING DATA?
  80.  
  81.              Now  that  we  have assigned values to the  six  simple
  82.         variables, we can do anything we desire with them.  In order
  83.         to keep this first example simple,  we will simply print out
  84.         the values to see if they really do exist as  assigned.   If
  85.         you carefully inspect the "printf" statements,  you will see
  86.         that there is nothing special about them.  The compound name
  87.         of each variable is specified because that is the only valid
  88.         name by which we can refer to these variables.
  89.  
  90.              Structures  are  a very useful method of grouping  data
  91.         together  in  order to make a program easier  to  write  and
  92.         understand.   This  first example is too simple to give  you
  93.         even  a hint of the value of using structures,  but continue
  94.         on  through  these lessons and eventually you will  see  the
  95.         value of using structures.
  96.  
  97.              Compile and run STRUCT1.C and observe the output.
  98.  
  99.                            AN ARRAY OF STRUCTURES
  100.  
  101.              Load  and  display the next  program  named  STRUCT2.C.
  102.         This  program  contains  the same  structure  definition  as
  103.         before  but  this  time we define an array of  12  variables
  104.         named "kids".   This program therefore contains 12 times 3 =
  105.         36  simple variables,  each of which can store one  item  of
  106.         data  provided  that  it is of the correct  type.   We  also
  107.         define a simple variable named "index" for use in the  "for"
  108.         loops.
  109.  
  110.              In order to assign each of the fields a value, we use a
  111.         "for"  loop  and  each  pass through  the  loop  results  in
  112.         assigning a value to three of the fields.  One pass  through
  113.         the  loop assigns all of the values for one of  the  "kids".
  114.         This would not be a very useful way to assign data in a real
  115.         situation, but a loop could read the data in from a file and
  116.         store it in the correct fields.  You might consider this the
  117.         crude beginning of a data base, which it is.
  118.  
  119.              In  the next few instructions of the program we  assign
  120.         new  values to some of the fields to illustrate  the  method
  121.  
  122.  
  123.                                   Page 77
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.                       Chapter 11 - Structures and Unions
  134.  
  135.  
  136.         used to accomplish this.  It should be self explanatory,  so
  137.         no additional comments will be given.
  138.  
  139.                        A RECENT UPGRADE TO THE C LANGUAGE
  140.  
  141.              Turbo C allows you to copy an entire structure with one
  142.         statement.  This  is  a  fairly recent  addition  to  the  C
  143.         language and will be a part of the ANSI standard when it  is
  144.         published, so you should feel free to use it with your Turbo
  145.         C  compiler.   Line 22 is an example of  using  a  structure
  146.         assignment.  In this statement, all 3 fields of kids[4]  are
  147.         copied into their respective fields of kids[10].
  148.  
  149.                    WE FINALLY DISPLAY ALL OF THE RESULTS
  150.  
  151.              The last few statements contain a for loop in which all
  152.         of  the generated values are displayed in a formatted  list.
  153.         Compile  and  run  the program to see if it  does  what  you
  154.         expect it to do.
  155.  
  156.                    USING POINTERS AND STRUCTURES TOGETHER
  157.  
  158.              Load  and  display  the  file named  STRUCT3.C  for  an
  159.         example of using pointers with structures.   This program is
  160.         identical  to the last program except that it uses  pointers
  161.         for some of the operations.
  162.  
  163.              The  first  difference shows up in  the  definition  of
  164.         variables  following  the  structure  definition.   In  this
  165.         program  we define a pointer named "point" which is  defined
  166.         as  a  pointer that points to the structure.   It  would  be
  167.         illegal  to  try to use this pointer to point to  any  other
  168.         variable  type.   There  is a very definite reason for  this
  169.         restriction  in  C as we have alluded to  earlier  and  will
  170.         review in the next few paragraphs.
  171.  
  172.              The  next difference is in the "for" loop where we  use
  173.         the pointer for accessing the data fields.  Since "kids"  is
  174.         a  pointer  variable that points to the  structure,  we  can
  175.         define "point" in terms of "kids".  The variable "kids" is a
  176.         constant so it cannot be changed in value, but "point" is  a
  177.         pointer  variable and can be assigned any  value  consistent
  178.         with  its being required to point to the structure.   If  we
  179.         assign  the  value of "kids" to "point" then  it  should  be
  180.         clear that it will point to the first element of the  array,
  181.         a structure containing three fields.
  182.  
  183.                              POINTER ARITHMETIC
  184.  
  185.              Adding  1 to "point" will now cause it to point to  the
  186.         second  field of the array because of the way  pointers  are
  187.  
  188.  
  189.                                   Page 78
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.                       Chapter 11 - Structures and Unions
  200.  
  201.  
  202.         handled in C.   The system knows that the structure contains
  203.         three  variables  and it knows how many memory elements  are
  204.         required to store the complete structure.   Therefore if  we
  205.         tell it to add one to the pointer,  it will actually add the
  206.         number  of  memory  elements  required to get  to  the  next
  207.         element of the array.   If, for example, we were to add 4 to
  208.         the  pointer,  it would advance the value of the  pointer  4
  209.         times the size of the structure,  resulting in it pointing 4
  210.         elements  farther  along the array.   This is the  reason  a
  211.         pointer  cannot be used to point to any data type other than
  212.         the one for which it was defined.
  213.  
  214.              Now to return to the program displayed on your monitor.
  215.         It  should be clear from the previous discussion that as  we
  216.         go through the loop, the pointer will point to the beginning
  217.         of  one of the array elements each time.   We can  therefore
  218.         use  the  pointer to reference the various elements  of  the
  219.         structure.   Referring to the elements of a structure with a
  220.         pointer occurs so often in C that a special method of  doing
  221.         that  was  devised.   Using "point->initial" is the same  as
  222.         using  "(*point).initial" which is really the way we did  it
  223.         in  the  last  two programs.  Remember that  *point  is  the
  224.         stored  data to which the pointer points and  the  construct
  225.         should be clear.  The "->" is made up of the minus sign  and
  226.         the greater than sign.
  227.  
  228.              Since the pointer points to the structure, we must once
  229.         again  define which of the elements we wish to refer to each
  230.         time  we use one of the elements of  the  structure.   There
  231.         are, as we have seen, several different methods of referring
  232.         to the members of the structure, and in the "for" loop  used
  233.         for output at the end of the program, we use three different
  234.         methods.   This  would be considered very  poor  programming
  235.         practice,  but  is done this way here to illustrate  to  you
  236.         that  they all lead to the same result.  This  program  will
  237.         probably   require  some  study  on  your  part   to   fully
  238.         understand,  but  it will be worth your time and  effort  to
  239.         grasp these principles.
  240.  
  241.              Lines  29  and  30  are  two  additional  examples   of
  242.         structure assignment for your benefit.
  243.  
  244.              Compile and run this program.
  245.  
  246.                         NESTED AND NAMED STRUCTURES
  247.  
  248.              Load and display the file named NESTED.C for an example
  249.         of  a nested structure.   The structures we have seen so far
  250.         have been very simple,  although useful.   It is possible to
  251.         define  structures  containing dozens and even  hundreds  or
  252.         thousands  of  elements but it would be to  the  programmers
  253.  
  254.  
  255.                                   Page 79
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.                       Chapter 11 - Structures and Unions
  266.  
  267.  
  268.         advantage not to define all of the elements at one pass  but
  269.         rather to use a hierarchical structure of definition.   This
  270.         will be illustrated with the program on your monitor.
  271.  
  272.              The  first  structure  contains three elements  but  is
  273.         followed by no variable name.  We therefore have not defined
  274.         any variables only a structure, but since we have included a
  275.         name  at the beginning of the structure,  the  structure  is
  276.         named  "person".   The name "person" can be used to refer to
  277.         the  structure  but not to any variable  of  this  structure
  278.         type.   It is therefore a new type that we have defined, and
  279.         we can use the new type in nearly the same way we use "int",
  280.         "char",  or  any  other  types that exist in  C.   The  only
  281.         restriction is that this new name must always be  associated
  282.         with the reserved word "struct".
  283.  
  284.              The  next  structure definition contains  three  fields
  285.         with the middle field being the previously defined structure
  286.         which we named "person".  The variable which has the type of
  287.         "person" is named "descrip".   So the new structure contains
  288.         two   simple   variables,   "grade"  and  a   string   named
  289.         "lunch[25]",  and  the  structure  named  "descrip".   Since
  290.         "descrip"  contains  three  variables,   the  new  structure
  291.         actually contains 5 variables.  This structure is also given
  292.         a name "alldat",  which is another type definition.  Finally
  293.         we  define an array of 53 variables each with the  structure
  294.         defined by "alldat",  and each with the name "student".   If
  295.         that is clear,  you will see that we have defined a total of
  296.         53 times 5 variables,  each of which is capable of storing a
  297.         value.
  298.  
  299.                              TWO MORE VARIABLES
  300.  
  301.              Since  we  have a new type definition we can use it  to
  302.         define  two  more variables.   The variables  "teacher"  and
  303.         "sub"  are  defined in line 16 to be variables of  the  type
  304.         "alldat",  so  that each of these two  variables  contain  5
  305.         fields which can store data.
  306.  
  307.                        NOW TO USE SOME OF THE FIELDS
  308.  
  309.              In  the next five lines of the program,  we will assign
  310.         values to each of the fields of "teacher".   The first field
  311.         is  the  "grade" field and is handled just  like  the  other
  312.         structures  we  have studied because it is not part  of  the
  313.         nested structure.  Next we wish to assign a value to her age
  314.         which  is  part of the nested structure.   To  address  this
  315.         field  we start with the variable name "teacher" to which we
  316.         append  the name of the group "descrip",  and then  we  must
  317.         define which field of the nested structure we are interested
  318.         in,  so  we append the name "age".   The teachers status  is
  319.  
  320.  
  321.                                   Page 80
  322.  
  323.  
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.                       Chapter 11 - Structures and Unions
  332.  
  333.  
  334.         handled in exactly the same manner as her age,  but the last
  335.         two  fields  are  assigned  strings using  the  string  copy
  336.         "strcpy" function which must be used for string  assignment.
  337.         Notice  that the variable names in the "strcpy" function are
  338.         still variable names even though they are made up of several
  339.         parts each.
  340.  
  341.              The variable "sub" is assigned nonsense values in  much
  342.         the  same  way,  but in a different order since they do  not
  343.         have to occur in any required order.   Finally, a few of the
  344.         "student"  variables  are assigned values  for  illustrative
  345.         purposes  and  the program ends.   None of  the  values  are
  346.         printed  for illustration since several were printed in  the
  347.         last examples.
  348.  
  349.                            MORE ABOUT STRUCTURES
  350.  
  351.              It is possible to continue nesting structures until you
  352.         get  totally confused.   If you define  them  properly,  the
  353.         computer  will  not get confused because there is no  stated
  354.         limit as to how many levels of nesting are  allowed.   There
  355.         is probably a practical limit of three beyond which you will
  356.         get confused, but the language has no limit.  In addition to
  357.         nesting, you can include as many structures as you desire in
  358.         any level of structures,  such as defining another structure
  359.         prior  to  "alldat" and using it in "alldat" in addition  to
  360.         using  "person".   The  structure named  "person"  could  be
  361.         included in "alldat" two or more times if desired,  as could
  362.         pointers to it.
  363.  
  364.              Structures can contain arrays of other structures which
  365.         in  turn  can  contain  arrays  of  simple  types  or  other
  366.         structures.   It  can go on and on until you lose all reason
  367.         to  continue.   I am only trying to illustrate to  you  that
  368.         structures  are  very valuable and you will find them  great
  369.         aids to programming if you use them wisely.  Be conservative
  370.         at first, and get bolder as you gain experience.
  371.  
  372.              More  complex structures will not be illustrated  here,
  373.         but  you will find examples of additional structures in  the
  374.         example  programs  included  in the  last  chapter  of  this
  375.         tutorial.     For   example,   see   the   "#include"   file
  376.         "STRUCT.DEF".
  377.  
  378.                               WHAT ARE UNIONS?
  379.  
  380.              Load the file named UNION1.C for an example of a union.
  381.         Simply stated,  a union allows you a way to look at the same
  382.         data  with  different types,  or to use the same  data  with
  383.         different names. Examine the program on your monitor.
  384.  
  385.  
  386.  
  387.                                   Page 81
  388.  
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.                       Chapter 11 - Structures and Unions
  398.  
  399.  
  400.              In this example we have two elements to the union,  the
  401.         first part being the integer named "value",  which is stored
  402.         as  a  two byte variable somewhere in the computers  memory.
  403.         The  second  element is made up of two  character  variables
  404.         named "first" and "second".   These two variables are stored
  405.         in  the  same storage locations that "value" is  stored  in,
  406.         because  that is what a union does.   A union allows you  to
  407.         store  different types of data in the same physical  storage
  408.         locations.  In this case, you could put an integer number in
  409.         "value",  then retrieve it in its two halves by getting each
  410.         half  using  the  two  names  "first"  and  "second".   This
  411.         technique is often used to pack data bytes together when you
  412.         are,  for  example,  combining  bytes  to  be  used  in  the
  413.         registers of the microprocessor.
  414.  
  415.              Accessing  the fields of the union are very similar  to
  416.         accessing the fields of a structure and will be left to  you
  417.         to determine by studying the example.
  418.  
  419.              One  additional  note  must  be given  here  about  the
  420.         program.   When  it is run using the Turbo C  compiler,  the
  421.         data  will  be  displayed with two leading f's  due  to  the
  422.         hexadecimal output promoting the char type variables to  int
  423.         and extending the sign bit to the left.  Converting the char
  424.         type data fields to int type fields prior to display  should
  425.         remove the leading f's from your display.  This will involve
  426.         defining  two new int type variables and assigning the  char
  427.         type  variables to them.  This will be left as  an  exercise
  428.         for  you.  Note that the same problem will come up in a  few
  429.         of the later files also.
  430.  
  431.              Compile and run this program and observe that the  data
  432.         is  read out as an "int" and as two "char"  variables.   The
  433.         "char" variables are reversed in order because of the way an
  434.         "int" variable is stored internally in your computer.  Don't
  435.         worry  about this.  It is not a problem but it can be a very
  436.         interesting area of study if you are so inclined.
  437.  
  438.                            ANOTHER UNION EXAMPLE
  439.  
  440.              Load  and  display the file named UNION2.C for  another
  441.         example of a union,  one which is much more common.  Suppose
  442.         you  wished to build a large database including  information
  443.         on many types of vehicles.  It would be silly to include the
  444.         number of propellers on a car,  or the number of tires on  a
  445.         boat.   In  order to keep all pertinent data,  however,  you
  446.         would  need  those  data points for their  proper  types  of
  447.         vehicles.   In  order to build an efficient data  base,  you
  448.         would need several different types of data for each vehicle,
  449.         some  of which would be common,  and some of which would  be
  450.  
  451.  
  452.  
  453.                                   Page 82
  454.  
  455.  
  456.  
  457.  
  458.  
  459.  
  460.  
  461.  
  462.  
  463.                       Chapter 11 - Structures and Unions
  464.  
  465.  
  466.         different.  That is exactly what we are doing in the example
  467.         program on your monitor.
  468.  
  469.              In this program,  we will define a complete  structure,
  470.         then  decide which of the various types can go into it.   We
  471.         will  start at the top and work our  way  down.   First,  we
  472.         define  a  few constants with the #defines,  and  begin  the
  473.         program  itself.   We define a structure named  "automobile"
  474.         containing  several fields which you should have no  trouble
  475.         recognizing, but we define no variables at this time.
  476.  
  477.                          A NEW CONCEPT, THE TYPEDEF
  478.  
  479.              Next  we  define a new type of data with  a  "typedef".
  480.         This  defines  a complete new type that can be used  in  the
  481.         same way that "int" or "char" can be used.   Notice that the
  482.         structure  has  no name,  but at the end where  there  would
  483.         normally be a variable name there is the name "BOATDEF".  We
  484.         now have a new type, "BOATDEF", that can be used to define a
  485.         structure anyplace we would like to.   Notice that this does
  486.         not  define  any  variables,  only a  new  type  definition.
  487.         Capitalizing  the name is a personal preference only and  is
  488.         not  a  C standard.   It makes the "typedef" look  different
  489.         from a variable name.
  490.  
  491.              We  finally come to the big structure that defines  our
  492.         data using the building blocks already defined  above.   The
  493.         structure is composed of 5 parts, two simple variables named
  494.         "vehicle" and "weight",  followed by the union,  and finally
  495.         the last two simple variables named "value" and "owner".  Of
  496.         course  the union is what we need to look at carefully here,
  497.         so focus on it for the moment.   You will notice that it  is
  498.         composed  of four parts,  the first part being the  variable
  499.         "car" which is a structure that we defined previously.   The
  500.         second  part is a variable named "boat" which is a structure
  501.         of the type "BOATDEF" previously defined.  The third part of
  502.         the  union is the variable "airplane" which is  a  structure
  503.         defined in place in the union.   Finally we come to the last
  504.  
  505.         part  of  the  union,  the variable named  "ship"  which  is
  506.         another structure of the type "BOATDEF".
  507.  
  508.              I  hope  it is obvious to you that all four could  have
  509.         been defined in any of the three ways shown,  but the  three
  510.         different  methods  were used to show you that any could  be
  511.         used.   In practice,  the clearest definition would probably
  512.         have occurred by using the "typedef" for each of the parts.
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.                                   Page 83
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.                       Chapter 11 - Structures and Unions
  530.  
  531.  
  532.                             WHAT DO WE HAVE NOW?
  533.  
  534.              We  now have a structure that can be used to store  any
  535.         of  four different kinds of data structures.   The  size  of
  536.         every  record will be the size of that record containing the
  537.         largest  union.   In this case part 1 is the  largest  union
  538.         because  it is composed of three integers,  the others being
  539.         composed  of  an integer and a character  each.   The  first
  540.         member  of this union would therefore determine the size  of
  541.         all structures of this type.  The resulting structure can be
  542.         used to store any of the four types of data, but it is up to
  543.         the  programmer  to  keep track of what is  stored  in  each
  544.         variable of this type.   The variable "vehicle" was designed
  545.         into  this  structure to keep track of the type  of  vehicle
  546.         stored here.   The four defines at the top of the page  were
  547.         designed  to  be  used  as indicators to be  stored  in  the
  548.         variable "vehicle".
  549.  
  550.              A  few  examples of how to use the resulting  structure
  551.         are given in the next few lines of the program.  Some of the
  552.         variables are defined and a few of them are printed out  for
  553.         illustrative purposes.
  554.  
  555.              The union is not used too frequently,  and almost never
  556.         by   beginning   programmers.    You   will   encounter   it
  557.         occasionally  so  it is worth your effort to at  least  know
  558.         what  it is.   You do not need to know the details of it  at
  559.         this time,  so don't spend too much time studying it.   When
  560.         you do have a need for a variant structure, a union, you can
  561.         learn it at that time. For your own benefit, however, do not
  562.         slight the structure. You should use the structure often.
  563.  
  564.  
  565.  
  566.  
  567.         PROGRAMMING EXERCISES
  568.  
  569.         1.   Define a named structure  containing a string field for
  570.              a name,  an integer for feet, and another for arms. Use
  571.              the new type to define an array of about 6 items.  Fill
  572.              the fields with data and print them out as follows.
  573.  
  574.              A human being has 2 legs and 2 arms.
  575.              A dog has 4 legs and 0 arms.
  576.              A television set has 4 legs and 0 arms.
  577.              A chair has 4 legs and 2 arms.
  578.              etc.
  579.  
  580.         2.   Rewrite  exercise 1 using  a pointer to print the  data
  581.              out.
  582.  
  583.  
  584.  
  585.                                   Page 84
  586.